package org.miyuki4j.cfgtool;

import lombok.extern.slf4j.Slf4j;

import java.util.*;

/**
 * @Desc
 * @Author miyuki4j
 * @Date 2025/7/26/星期六 14:48
 * @Version 1.0
 */
@SuppressWarnings({"rawtypes", "unchecked"})
@Slf4j
public class CfgManager {


    private static final Map<String, TableImportData> IMPORT_DATAS_MAP = new HashMap<>();

    private static final Map<Class<? extends Conf>, NavigableMap<? extends Comparable, ? extends Conf>> CONF_MAP = new HashMap<>();

    public static void importData() throws Exception {
        List<TableImportData> tableImportDatas = TableUtil.importDatas();
        for (TableImportData tableImportData : tableImportDatas) {
            TableImportData oldData = IMPORT_DATAS_MAP.get(tableImportData.getFullClassName());
            if (oldData != null) {
                oldData.merge(tableImportData);
            } else {
                IMPORT_DATAS_MAP.put(tableImportData.getFullClassName(), tableImportData);
            }
        }
    }

    public static void loadConf() throws Exception {
        Map<Class<? extends Conf>, List<Conf>> confs = TableUtil.loadConfs();
        for (Map.Entry<Class<? extends Conf>, List<Conf>> entry : confs.entrySet()) {
            NavigableMap<Comparable, Conf> confMap = new TreeMap<>();
            for (Conf conf : entry.getValue()) {
                Comparable id = conf.getId();
                confMap.put(id, conf);
            }
            CONF_MAP.put(entry.getKey(), confMap);
        }
        onAllLoaded();
    }

    public static TableImportData getImportData(String fullClassName) {
        return IMPORT_DATAS_MAP.getOrDefault(fullClassName, new TableImportData(fullClassName));
    }

    public static <ID extends Comparable<ID>, T extends Conf> T getConf(Class<T> clazz, ID id) {
        NavigableMap<ID, T> confMap = (NavigableMap<ID, T>) CONF_MAP.get(clazz);
        if (confMap == null || confMap.isEmpty()) {
            return null;
        }
        return confMap.get(id);
    }

    public static <ID extends Comparable<ID>, T extends Conf> Optional<T> getConfOptional(Class<T> clazz, ID id) {
        NavigableMap<ID, T> confMap = (NavigableMap<ID, T>) CONF_MAP.get(clazz);
        if (confMap == null || confMap.isEmpty()) {
            return Optional.empty();
        }
        return Optional.of(confMap.get(id));
    }

    public static <ID extends Comparable<ID>, T extends Conf<ID>> NavigableMap<ID, T> getConfMap(Class<T> tClazz) {
        return (NavigableMap<ID, T>) CONF_MAP.getOrDefault(tClazz, Collections.emptyNavigableMap());
    }


    private static void onAllLoaded() throws Exception {
        for (NavigableMap<? extends Comparable, ? extends Conf> map : CONF_MAP.values()) {
            for (Conf conf : map.values()) {
                conf.onAllLoaded();
            }
        }
    }

}
